package com.ccteam.fluidmusic.ui.search

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import com.ccteam.fluidmusic.NavMoreMusicDirections
import com.ccteam.fluidmusic.databinding.FragmentSearchResultMusicBinding
import com.ccteam.fluidmusic.fluidmusic.common.utils.MediaIDHelper
import com.ccteam.fluidmusic.view.adapters.GlobalDefaultMusicItemAdapter
import com.ccteam.fluidmusic.view.adapters.paging.CustomLoadStateAdapter
import com.ccteam.fluidmusic.view.bean.MoreInfoData
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment.Companion.RESULT_MOMENTS_TYPE_KEY
import com.ccteam.fluidmusic.ui.artist.ArtistDetailMusicPagerFragment
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_MUSIC
import com.ccteam.shared.result.moment.MomentListItem
import com.ccteam.shared.result.music.DefaultMusicItem
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/3/16
 */
@AndroidEntryPoint
class SearchMusicResultFragment: Fragment() {

    private var _binding: FragmentSearchResultMusicBinding? = null
    private val binding: FragmentSearchResultMusicBinding get() = _binding!!

    private val homeSearchMusicResultViewModel by viewModels<HomeSearchMusicResultViewModel>()
    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    /**
     * 是否是第一次加载
     * 如果不是第一次启动，则需要在分页数据更新时再次刷新一下数据，否则正在播放内容不会正确进行同步
     */
    private var isFirstLoad: Boolean = true

    companion object {
        @JvmStatic
        fun newInstance(searchKey: String,type: Int): SearchMusicResultFragment {
            return SearchMusicResultFragment().apply {
                arguments = Bundle().apply {
                    putString(SEARCH_KEY, searchKey)
                    putInt("type", type)
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentSearchResultMusicBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val dataAdapter = ArtistDetailMusicPagerFragment.ArtistMusicListAdapter(callback)
        binding.rvMusicList.adapter = dataAdapter.withLoadStateFooter(
            CustomLoadStateAdapter(dataAdapter,true){
                dataAdapter.retry()
            }
        )

        homeSearchMusicResultViewModel.musicList.observe(viewLifecycleOwner, {
            // 如果不是第一次加载，而是回退到此界面，则手动刷新一下数据
            if(!isFirstLoad){
                viewLifecycleOwner.lifecycleScope.launch {
                    homeSearchMusicResultViewModel.refreshNowPlaying()
                    isFirstLoad = true
                }
            }
            dataAdapter.submitData(viewLifecycleOwner.lifecycle,it)
        })

        viewLifecycleOwner.lifecycleScope.launch {
            dataAdapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && dataAdapter.itemCount < 1)
            }
        }

        binding.statusView.setRetryClickListener {
            dataAdapter.refresh()
        }
    }

    private val callback = object: GlobalDefaultMusicItemAdapter.DefaultMusicItemClickCallback{
        override fun musicItemClicked(item: DefaultMusicItem) {
            if(homeSearchMusicResultViewModel.type == AddOnlineMediaFragment.TYPE_SEARCH){
                mainActivityViewModel.addQueueItem(item.mediaId,MediaIDHelper.ONLINE_MEDIA_SEARCH,MediaIDHelper.PLAYLIST_ADD_TYPE_NOW_PLAY)
            } else {
                parentFragment?.setFragmentResult(RESULT_MOMENTS_TYPE_KEY, bundleOf(
                    RESULT_MOMENTS_TYPE_KEY to MomentListItem.MomentShareItem(
                        item.mediaId, MOMENT_SHARE_TYPE_MUSIC,item.title
                        ,item.subtitle,item.albumArtUri
                    )
                ))
                findNavController().navigateUp()
            }
        }

        override fun moreClicked(item: DefaultMusicItem) {
            findNavController().navigate(NavMoreMusicDirections.actionGlobalMusicMoreBottomSheetFragment(
                MoreInfoData(MediaIDHelper.ONLINE_MEDIA_SEARCH,item.mediaId,item.title,item.subtitle,
                    false,item.albumId,item.artistInfo,item.albumArtUri)
            ))
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()

        isFirstLoad = false
        _binding = null
    }
}